package com.nwpu.intimacy.chat;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sun.misc.BASE64Decoder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.ConsoleMessage.MessageLevel;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nwpu.intimacy.R;
import com.nwpu.intimacy.adapter.MessageAdapter;
import com.nwpu.intimacy.chat.adapter.ExpressionAdapter;
import com.nwpu.intimacy.chat.adapter.ExpressionPagerAdapter;
import com.nwpu.intimacy.chat.util.CommonUtils;
import com.nwpu.intimacy.chat.util.SmileUtils;
import com.nwpu.intimacy.chat.widget.ExpandGridView;
import com.nwpu.intimacy.chat.widget.PasteEditText;
import com.nwpu.intimacy.utils.CacheUtil;

public class ChatActivity extends Activity implements OnClickListener {

	private static final String IP = "10.128.51.203";
	private static final int PORT = 9000;

	private static final int REQUEST_CODE_EMPTY_HISTORY = 2;
	public static final int REQUEST_CODE_CONTEXT_MENU = 3;
	private static final int REQUEST_CODE_MAP = 4;
	public static final int REQUEST_CODE_TEXT = 5;
	public static final int REQUEST_CODE_VOICE = 6;
	public static final int REQUEST_CODE_PICTURE = 7;
	public static final int REQUEST_CODE_LOCATION = 8;
	public static final int REQUEST_CODE_NET_DISK = 9;
	public static final int REQUEST_CODE_FILE = 10;
	public static final int REQUEST_CODE_COPY_AND_PASTE = 11;
	public static final int REQUEST_CODE_PICK_VIDEO = 12;
	public static final int REQUEST_CODE_DOWNLOAD_VIDEO = 13;
	public static final int REQUEST_CODE_VIDEO = 14;
	public static final int REQUEST_CODE_DOWNLOAD_VOICE = 15;
	public static final int REQUEST_CODE_SELECT_USER_CARD = 16;
	public static final int REQUEST_CODE_SEND_USER_CARD = 17;
	public static final int REQUEST_CODE_CAMERA = 18;
	public static final int REQUEST_CODE_LOCAL = 19;
	public static final int REQUEST_CODE_CLICK_DESTORY_IMG = 20;
	public static final int REQUEST_CODE_GROUP_DETAIL = 21;
	public static final int REQUEST_CODE_SELECT_VIDEO = 23;
	public static final int REQUEST_CODE_SELECT_FILE = 24;
	public static final int REQUEST_CODE_ADD_TO_BLACKLIST = 25;

	public static final int RESULT_CODE_COPY = 1;
	public static final int RESULT_CODE_DELETE = 2;
	public static final int RESULT_CODE_FORWARD = 3;
	public static final int RESULT_CODE_OPEN = 4;
	public static final int RESULT_CODE_DWONLOAD = 5;
	public static final int RESULT_CODE_TO_CLOUD = 6;
	public static final int RESULT_CODE_EXIT_GROUP = 7;

	public static final int CHATTYPE_SINGLE = 1;
	public static final int CHATTYPE_GROUP = 2;

	public static final String COPY_IMAGE = "EASEMOBIMG";

	private TextView chatName;

	private View recordingContainer;
	private ImageView micImage;
	private TextView recordingHint;
	private static ListView listView;
	private PasteEditText mEditTextContent;
	private View buttonSetModeKeyboard;
	private View buttonSetModeVoice;
	private View buttonSend;
	private View buttonPressToSpeak;

	private LinearLayout emojiIconContainer;
	private LinearLayout btnContainer;

	private RelativeLayout edittext_layout;
	private ViewPager expressionViewpager;
	private ImageView iv_emoticons_normal;
	private ImageView iv_emoticons_checked;
	private ProgressBar loadmorePB;
	private Button btnMore;

	private View more;
	private Drawable[] micImages;
	private List<String> reslist;
	// private PowerManager.WakeLock wakeLock;
	private InputMethodManager manager;
	private File cameraFile;

	private String friendName;
	private Bitmap myPhoto;
	private Bitmap friendPhoto;

	private SharedPreferences sp_userMessage;

	private String mFileName_voice = null; // 录音存储位置
	private MediaRecorder mRecorder = null; // 用于完成录音

	private static MessageAdapter adapter;
	private static List<ListData> messageLists;

	private double oldTime = 0;

	@SuppressLint("HandlerLeak")
	private Handler micImageHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			// 切换msg切换图片
			micImage.setImageDrawable(micImages[msg.what]);
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat);

		getActionBar().hide();

		sp_userMessage = this.getSharedPreferences("userMessage",
				Context.MODE_PRIVATE);

		messageLists = new ArrayList<ListData>();
		friendName = getIntent().getExtras().getString("friendname");

		initLayout();

		getChatHistory();

		manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		// wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
		// .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");

		chatName.setText(friendName);

		friendPhoto = CacheUtil.GetFromFile(friendName, "FriendPhoto");
		myPhoto = CacheUtil.GetFromFile(
				sp_userMessage.getString("USER_NAME", ""), "Photo");

	}

	public void initLayout() {

		chatName = (TextView) findViewById(R.id.name_chat);
		recordingContainer = findViewById(R.id.recording_container);
		micImage = (ImageView) findViewById(R.id.mic_image);
		recordingHint = (TextView) findViewById(R.id.recording_hint);
		listView = (ListView) findViewById(R.id.list);
		mEditTextContent = (PasteEditText) findViewById(R.id.et_sendmessage);
		buttonSetModeKeyboard = findViewById(R.id.btn_set_mode_keyboard);
		edittext_layout = (RelativeLayout) findViewById(R.id.edittext_layout);
		buttonSetModeVoice = findViewById(R.id.btn_set_mode_voice);
		buttonSend = findViewById(R.id.btn_send);
		buttonPressToSpeak = findViewById(R.id.btn_press_to_speak);
		expressionViewpager = (ViewPager) findViewById(R.id.vPager);
		emojiIconContainer = (LinearLayout) findViewById(R.id.ll_face_container);
		btnContainer = (LinearLayout) findViewById(R.id.ll_btn_container);
		iv_emoticons_normal = (ImageView) findViewById(R.id.iv_emoticons_normal);
		iv_emoticons_checked = (ImageView) findViewById(R.id.iv_emoticons_checked);
		loadmorePB = (ProgressBar) findViewById(R.id.pb_load_more);
		btnMore = (Button) findViewById(R.id.btn_more);

		iv_emoticons_normal.setVisibility(View.VISIBLE);
		iv_emoticons_checked.setVisibility(View.INVISIBLE);
		more = findViewById(R.id.more);
		edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_normal);

		iv_emoticons_normal.setOnClickListener(this);
		iv_emoticons_checked.setOnClickListener(this);

		adapter = new MessageAdapter(messageLists, this);
		listView.setAdapter(adapter);

		// 动画资源文件,用于录制语音时
		micImages = new Drawable[] {
				getResources().getDrawable(R.drawable.record_animate_01),
				getResources().getDrawable(R.drawable.record_animate_02),
				getResources().getDrawable(R.drawable.record_animate_03),
				getResources().getDrawable(R.drawable.record_animate_04),
				getResources().getDrawable(R.drawable.record_animate_05),
				getResources().getDrawable(R.drawable.record_animate_06),
				getResources().getDrawable(R.drawable.record_animate_07),
				getResources().getDrawable(R.drawable.record_animate_08),
				getResources().getDrawable(R.drawable.record_animate_09),
				getResources().getDrawable(R.drawable.record_animate_10),
				getResources().getDrawable(R.drawable.record_animate_11),
				getResources().getDrawable(R.drawable.record_animate_12),
				getResources().getDrawable(R.drawable.record_animate_13),
				getResources().getDrawable(R.drawable.record_animate_14), };

		// 表情list
		reslist = getExpressionRes(35);

		// 初始化表情viewpager
		List<View> views = new ArrayList<View>();
		View gv1 = getGridChildView(1);
		View gv2 = getGridChildView(2);
		views.add(gv1);
		views.add(gv2);
		expressionViewpager.setAdapter(new ExpressionPagerAdapter(views));
		edittext_layout.requestFocus();

		buttonPressToSpeak.setOnTouchListener(new PressToSpeakListen());
		mEditTextContent.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					edittext_layout
							.setBackgroundResource(R.drawable.input_bar_bg_active);
				} else {
					edittext_layout
							.setBackgroundResource(R.drawable.input_bar_bg_normal);
				}

			}
		});
		mEditTextContent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				edittext_layout
						.setBackgroundResource(R.drawable.input_bar_bg_active);
				more.setVisibility(View.GONE);
				iv_emoticons_normal.setVisibility(View.VISIBLE);
				iv_emoticons_checked.setVisibility(View.INVISIBLE);
				emojiIconContainer.setVisibility(View.GONE);
				btnContainer.setVisibility(View.GONE);
			}
		});
		// 监听文字框
		mEditTextContent.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!TextUtils.isEmpty(s)) {
					btnMore.setVisibility(View.GONE);
					buttonSend.setVisibility(View.VISIBLE);
				} else {
					btnMore.setVisibility(View.VISIBLE);
					buttonSend.setVisibility(View.GONE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

	}

	/**
	 * 消息图标点击事件
	 * 
	 * @param view
	 */
	public void onClick(View view) {

		int id = view.getId();
		if (id == R.id.btn_send) {// 点击发送按钮(发文字和表情)

			String s = mEditTextContent.getText().toString();
			sendText(s);

		} else if (id == R.id.btn_take_picture) {

			selectPicFromCamera();// 点击照相图标

		} else if (id == R.id.btn_picture) {

			selectPicFromLocal(); // 点击图片图标

		} else if (id == R.id.iv_emoticons_normal) { // 点击显示表情框

			more.setVisibility(View.VISIBLE);
			iv_emoticons_normal.setVisibility(View.INVISIBLE);
			iv_emoticons_checked.setVisibility(View.VISIBLE);
			btnContainer.setVisibility(View.GONE);
			emojiIconContainer.setVisibility(View.VISIBLE);
			hideKeyboard();

		} else if (id == R.id.iv_emoticons_checked) { // 点击隐藏表情框

			iv_emoticons_normal.setVisibility(View.VISIBLE);
			iv_emoticons_checked.setVisibility(View.INVISIBLE);
			btnContainer.setVisibility(View.VISIBLE);
			emojiIconContainer.setVisibility(View.GONE);
			more.setVisibility(View.GONE);

		} else if (id == R.id.btn_file) { // 点击文件图标

			selectFileFromLocal();

		}
	}

	/**
	 * 照相获取图片
	 */
	public void selectPicFromCamera() {
		if (!CommonUtils.isExitsSdcard()) {
			Toast.makeText(getApplicationContext(), "SD卡不存在，不能拍照",
					Toast.LENGTH_SHORT).show();
			return;
		}

		cameraFile = new File("/sdcard/Intimacy/user/Send/Photo",
				sp_userMessage.getString("USER_NAME", "") + friendName
						+ +System.currentTimeMillis() + ".jpg");
		cameraFile.getParentFile().mkdirs();
		startActivityForResult(
				new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(
						MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
				REQUEST_CODE_CAMERA);
	}

	/**
	 * 选择文件
	 */
	private void selectFileFromLocal() {
		Intent intent = null;
		if (Build.VERSION.SDK_INT < 19) {
			intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("*/*");
			intent.addCategory(Intent.CATEGORY_OPENABLE);

		} else {

			intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("*/*");
			intent.addCategory(Intent.CATEGORY_OPENABLE);
			// intent = new Intent(
			// Intent.ACTION_PICK,
			// android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		}
		startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
	}

	/**
	 * 从图库获取图片
	 */
	public void selectPicFromLocal() {
		Intent intent;
		if (Build.VERSION.SDK_INT < 19) {
			intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("image/*");

		} else {

			intent = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		}
		startActivityForResult(intent, REQUEST_CODE_LOCAL);
	}

	/**
	 * 显示语音图标按钮
	 * 
	 * @param view
	 */
	public void setModeVoice(View view) {

		hideKeyboard();
		edittext_layout.setVisibility(View.GONE);
		more.setVisibility(View.GONE);
		view.setVisibility(View.GONE);
		buttonSetModeKeyboard.setVisibility(View.VISIBLE);
		buttonSend.setVisibility(View.GONE);
		btnMore.setVisibility(View.VISIBLE);
		buttonPressToSpeak.setVisibility(View.VISIBLE);
		iv_emoticons_normal.setVisibility(View.VISIBLE);
		iv_emoticons_checked.setVisibility(View.INVISIBLE);
		btnContainer.setVisibility(View.VISIBLE);
		emojiIconContainer.setVisibility(View.GONE);

	}

	/**
	 * 显示键盘图标
	 * 
	 * @param view
	 */
	public void setModeKeyboard(View view) {

		edittext_layout.setVisibility(View.VISIBLE);
		more.setVisibility(View.GONE);
		view.setVisibility(View.GONE);
		buttonSetModeVoice.setVisibility(View.VISIBLE);
		// mEditTextContent.setVisibility(View.VISIBLE);
		mEditTextContent.requestFocus();
		// buttonSend.setVisibility(View.VISIBLE);
		buttonPressToSpeak.setVisibility(View.GONE);
		if (TextUtils.isEmpty(mEditTextContent.getText())) {
			btnMore.setVisibility(View.VISIBLE);
			buttonSend.setVisibility(View.GONE);
		} else {
			btnMore.setVisibility(View.GONE);
			buttonSend.setVisibility(View.VISIBLE);
		}

	}

	/**
	 * 显示或隐藏图标按钮页
	 * 
	 * @param view
	 */
	public void more(View view) {
		if (more.getVisibility() == View.GONE) {
			System.out.println("more gone");
			hideKeyboard();
			more.setVisibility(View.VISIBLE);
			btnContainer.setVisibility(View.VISIBLE);
			emojiIconContainer.setVisibility(View.GONE);
		} else {
			if (emojiIconContainer.getVisibility() == View.VISIBLE) {
				emojiIconContainer.setVisibility(View.GONE);
				btnContainer.setVisibility(View.VISIBLE);
				iv_emoticons_normal.setVisibility(View.VISIBLE);
				iv_emoticons_checked.setVisibility(View.INVISIBLE);
			} else {
				more.setVisibility(View.GONE);
			}

		}

	}

	/**
	 * 点击文字输入框
	 * 
	 * @param v
	 */
	public void editClick(View v) {
		listView.setSelection(listView.getCount() - 1);
		if (more.getVisibility() == View.VISIBLE) {
			more.setVisibility(View.GONE);
			iv_emoticons_normal.setVisibility(View.VISIBLE);
			iv_emoticons_checked.setVisibility(View.INVISIBLE);
		}

	}

	/**
	 * 隐藏软键盘
	 */
	private void hideKeyboard() {
		if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getCurrentFocus() != null)
				manager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	/**
	 * 返回
	 * 
	 * @param view
	 */
	public void back(View view) {
		// if(type==3){
		// startActivity(new
		// Intent(getApplicationContext(),MyGroupActivity.class));
		// finish();
		// }else if(type==2){
		// startActivity(new
		// Intent(getApplicationContext(),ContactListActivity.class));
		// finish();
		// }else if(type==1){
		// startActivity(new
		// Intent(getApplicationContext(),MainActivity.class));
		// finish();
		// }else{
		finish();
		// }
	}

	/**
	 * 覆盖手机返回键
	 */
	@Override
	public void onBackPressed() {
		if (more.getVisibility() == View.VISIBLE) {
			more.setVisibility(View.GONE);
			iv_emoticons_normal.setVisibility(View.VISIBLE);
			iv_emoticons_checked.setVisibility(View.INVISIBLE);
		} else {
			// if(type==3){
			// startActivity(new
			// Intent(getApplicationContext(),MyGroupActivity.class));
			// finish();
			// }else if(type==2){
			// startActivity(new
			// Intent(getApplicationContext(),ContactListActivity.class));
			// finish();
			// }else if(type==1){
			// startActivity(new
			// Intent(getApplicationContext(),MainActivity.class));
			// finish();
			// }else{
			finish();
			// }

			super.onBackPressed();
		}
	}

	/**
	 * 按住说话listener
	 * 
	 */
	class PressToSpeakListen implements View.OnTouchListener {
		@SuppressLint({ "ClickableViewAccessibility", "Wakelock" })
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (!CommonUtils.isExitsSdcard()) {
					Toast.makeText(ChatActivity.this, "发送语音需要sdcard支持！",
							Toast.LENGTH_SHORT).show();
					return false;
				}
				try {
					v.setPressed(true);
					// wakeLock.acquire();

					recordingContainer.setVisibility(View.VISIBLE);
					recordingHint
							.setText(getString(R.string.move_up_to_cancel));
					recordingHint.setBackgroundColor(Color.TRANSPARENT);

					// micImageHandler.start();

					startVoice();

				} catch (Exception e) {
					e.printStackTrace();
					v.setPressed(false);
					// if (wakeLock.isHeld())
					// wakeLock.release();

					recordingContainer.setVisibility(View.INVISIBLE);
					Toast.makeText(ChatActivity.this, R.string.recoding_fail,
							Toast.LENGTH_SHORT).show();
					return false;
				}

				return true;
			case MotionEvent.ACTION_MOVE: {
				if (event.getY() < 0) {
					recordingHint
							.setText(getString(R.string.release_to_cancel));
					recordingHint
							.setBackgroundResource(R.drawable.recording_text_hint_bg);
				} else {
					recordingHint
							.setText(getString(R.string.move_up_to_cancel));
					recordingHint.setBackgroundColor(Color.TRANSPARENT);

				}
				return true;
			}
			case MotionEvent.ACTION_UP:
				v.setPressed(false);
				recordingContainer.setVisibility(View.INVISIBLE);

				stopVoice();

				// if (wakeLock.isHeld())
				// wakeLock.release();
				if (event.getY() < 0) {

				} else {

					// stop recording and send voice file

					try {

						File file = new File(mFileName_voice);

						long length = file.length();

						if (length > 0) {

							sendVoice();

						} else {
							Toast.makeText(getApplicationContext(), "录音时间太短",
									Toast.LENGTH_SHORT).show();
						}

					} catch (Exception e) {
						e.printStackTrace();

						Log.e("tag...................", e.toString());

						Toast.makeText(ChatActivity.this, "发送失败，请检测服务器是否连接",
								Toast.LENGTH_SHORT).show();
					}

				}
				return true;
			default:
				recordingContainer.setVisibility(View.INVISIBLE);

				return false;
			}
		}
	}

	/**
	 * 开始录音
	 */
	private void startVoice() {
		// 设置录音保存路径

		try {

			mFileName_voice = "/sdcard/Intimacy/user/Send/Voice/"
					+ UUID.randomUUID().toString() + ".amr";
			String state = android.os.Environment.getExternalStorageState();
			if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {

				Log.i("voice", "SD Card is not mounted,It is  " + state + ".");

			}

			File directory = new File(mFileName_voice).getParentFile();

			if (!directory.exists() && !directory.mkdirs()) {

				Log.i("voice", "Path to file could not be created");

			}
			Toast.makeText(getApplicationContext(), "开始录音", 0).show();

			mRecorder = new MediaRecorder(); // Create MediaRecorder
			mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
			mRecorder.setOutputFile(mFileName_voice);
			mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);

			mRecorder.prepare();

			mRecorder.start();

		} catch (IOException e) {

			Log.e("voice", "prepare() failed");

		}

	}

	/**
	 * 停止录音
	 */
	private void stopVoice() {

		mRecorder.stop();
		mRecorder.release();
		mRecorder = null;

	}

	/**
	 * 获取表情的gridview的子view
	 * 
	 * @param i
	 * @return
	 */
	private View getGridChildView(int i) {
		View view = View.inflate(this, R.layout.expression_gridview, null);
		ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
		List<String> list = new ArrayList<String>();
		if (i == 1) {
			List<String> list1 = reslist.subList(0, 20);
			list.addAll(list1);
		} else if (i == 2) {
			list.addAll(reslist.subList(20, reslist.size()));
		}
		list.add("delete_expression");
		final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this,
				1, list);
		gv.setAdapter(expressionAdapter);
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String filename = expressionAdapter.getItem(position);
				try {
					// 文字输入框可见时，才可输入表情
					// 按住说话可见，不让输入表情
					if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) {

						if (filename != "delete_expression") { // 不是删除键，显示表情
							// 这里用的反射，所以混淆的时候不要混淆SmileUtils这个类
							@SuppressWarnings("rawtypes")
							Class clz = Class
									.forName("com.nwpu.intimacy.chat.util.SmileUtils");
							Field field = clz.getField(filename);
							mEditTextContent.append(SmileUtils.getSmiledText(
									ChatActivity.this, (String) field.get(null)));
						} else { // 删除文字或者表情
							if (!TextUtils.isEmpty(mEditTextContent.getText())) {

								int selectionStart = mEditTextContent
										.getSelectionStart();// 获取光标的位置
								if (selectionStart > 0) {
									String body = mEditTextContent.getText()
											.toString();
									String tempStr = body.substring(0,
											selectionStart);
									int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
									if (i != -1) {
										CharSequence cs = tempStr.substring(i,
												selectionStart);
										if (SmileUtils.containsKey(cs
												.toString()))
											mEditTextContent.getEditableText()
													.delete(i, selectionStart);
										else
											mEditTextContent.getEditableText()
													.delete(selectionStart - 1,
															selectionStart);
									} else {
										mEditTextContent.getEditableText()
												.delete(selectionStart - 1,
														selectionStart);
									}
								}
							}

						}
					}
				} catch (Exception e) {
				}

			}
		});
		return view;
	}

	public List<String> getExpressionRes(int getSum) {
		List<String> reslist = new ArrayList<String>();
		for (int x = 1; x <= getSum; x++) {
			String filename = "ee_" + x;

			reslist.add(filename);

		}
		return reslist;

	}

	/**
	 * 发送文本消息
	 * 
	 */
	private void sendText(String content) {

		if (content.length() > 0) {

			try {

				JSONArray sendArray = new JSONArray();
				JSONObject sendObject = new JSONObject();

				double time = System.currentTimeMillis();

				sendObject.put("sendid",
						sp_userMessage.getString("USER_NAME", ""));
				sendObject.put("receiveid", friendName);
				sendObject.put("message", content);
				sendObject.put("time", time);
				sendObject.put("type", 1);
				sendArray.put(sendObject);

				sendMessage(sendArray);

				ListData listData;
				listData = new ListData(friendName, sp_userMessage.getString(
						"USER_NAME", ""), content, ListData.SEND,
						getTime(time), friendPhoto, myPhoto, 1);
				messageLists.add(listData);

				adapter.notifyDataSetChanged();
				listView.setSelection(listView.getCount() - 1);

				JSONObject jsonObject = new JSONObject();
				jsonObject.put("sendid",
						sp_userMessage.getString("USER_NAME", ""));
				jsonObject.put("receiveid", friendName);
				jsonObject.put("message", content);
				jsonObject.put("time", time);
				jsonObject.put("flag", ListData.SEND);
				jsonObject.put("type", 1);
				storeToFile(jsonObject);

				mEditTextContent.setText("");

				setResult(RESULT_OK);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	/**
	 * 发送语音
	 * 
	 * @param filePath
	 * @param fileName
	 * @param length
	 * @param isResend
	 */
	private void sendVoice() {

		try {

			double time = System.currentTimeMillis();

			JSONArray sendArray = new JSONArray();
			JSONObject sendObject = new JSONObject();
			sendObject.put("sendid", sp_userMessage.getString("USER_NAME", ""));
			sendObject.put("receiveid", friendName);
			sendObject.put("message", filetoString(mFileName_voice));
			sendObject.put("time", time);
			sendObject.put("type", 3);
			sendArray.put(sendObject);

			sendMessage(sendArray);

			ListData listData;
			listData = new ListData(friendName, sp_userMessage.getString(
					"USER_NAME", ""), mFileName_voice, ListData.SEND,
					getTime(time), friendPhoto, myPhoto, 3);
			messageLists.add(listData);

			adapter.notifyDataSetChanged();
			listView.setSelection(listView.getCount() - 1);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("sendid", sp_userMessage.getString("USER_NAME", ""));
			jsonObject.put("receiveid", friendName);
			jsonObject.put("message", mFileName_voice);
			jsonObject.put("time", time);
			jsonObject.put("flag", ListData.SEND);
			jsonObject.put("type", 3);
			storeToFile(jsonObject);

			setResult(RESULT_OK);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 发送图片
	 * 
	 * @param filePath
	 */
	private void sendPicture(String filePath, int i) {

		try {

			Bitmap bitmap = null;

			if (i == 0) {

				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inJustDecodeBounds = true;
				// 获取这个图片的宽和高
				bitmap = BitmapFactory.decodeFile(filePath, options); // 此时返回bm为空
				options.inJustDecodeBounds = false;
				// 计算缩放比
				int be = (int) (options.outHeight / (float) 200);
				if (be <= 0)
					be = 1;
				options.inSampleSize = 2; // 图片长宽各缩小二分之一
				// 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false哦
				bitmap = BitmapFactory.decodeFile(filePath, options);
				int w = bitmap.getWidth();
				int h = bitmap.getHeight();
				System.out.println(w + " " + h);

				File file = new File(filePath);
				try {
					FileOutputStream out = new FileOutputStream(file);
					if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
						out.flush();
						out.close();
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			} else if (i == 1) {

				FileInputStream fis = new FileInputStream(filePath);

				bitmap = BitmapFactory.decodeStream(fis);

				String str = sp_userMessage.getString("USER_NAME", "")
						+ friendName + System.currentTimeMillis();

				CacheUtil.WriteToFile(str, bitmap, "Send" + "/" + "Photo");

				filePath = "/sdcard/Intimacy/user/" + "Send" + "/" + "Photo"
						+ "/" + str + ".jpg";

			}

			double time = System.currentTimeMillis();

			JSONArray sendArray = new JSONArray();
			JSONObject sendObject = new JSONObject();
			sendObject.put("sendid", sp_userMessage.getString("USER_NAME", ""));
			sendObject.put("receiveid", friendName);
			sendObject.put("message", bitmaptoString(bitmap));
			sendObject.put("time", time);
			sendObject.put("type", 2);
			sendArray.put(sendObject);

			sendMessage(sendArray);

			listView.setSelection(ListView.FOCUS_DOWN);

			ListData listData;
			listData = new ListData(friendName, sp_userMessage.getString(
					"USER_NAME", ""), filePath, ListData.SEND, getTime(time),
					friendPhoto, myPhoto, 2);
			messageLists.add(listData);

			adapter.notifyDataSetChanged();
			listView.setSelection(listView.getCount() - 1);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("sendid", sp_userMessage.getString("USER_NAME", ""));
			jsonObject.put("receiveid", friendName);
			jsonObject.put("message", filePath);
			jsonObject.put("time", time);
			jsonObject.put("flag", ListData.SEND);
			jsonObject.put("type", 2);
			storeToFile(jsonObject);

			setResult(RESULT_OK);

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 根据图库图片uri发送图片
	 * 
	 * @param selectedImage
	 */
	private void sendPicByUri(Uri selectedImage) {
		// String[] filePathColumn = { MediaStore.Images.Media.DATA };
		Cursor cursor = getContentResolver().query(selectedImage, null, null,
				null, null);
		if (cursor != null) {
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex("_data");
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
			cursor = null;

			if (picturePath == null || picturePath.equals("null")) {
				Toast toast = Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				return;
			}
			sendPicture(picturePath, 1);
		} else {
			File file = new File(selectedImage.getPath());
			if (!file.exists()) {
				Toast toast = Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				return;

			}
			sendPicture(file.getAbsolutePath(), 1);
		}

	}

	/**
	 * 发送文件
	 * 
	 * @param uri
	 */
	private void sendFile(Uri uri) {
		String filePath = null;
		if ("content".equalsIgnoreCase(uri.getScheme())) {
			String[] projection = { "_data" };
			Cursor cursor = null;

			try {
				cursor = getContentResolver().query(uri, projection, null,
						null, null);
				int column_index = cursor.getColumnIndexOrThrow("_data");
				if (cursor.moveToFirst()) {
					filePath = cursor.getString(column_index);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if ("file".equalsIgnoreCase(uri.getScheme())) {
			filePath = uri.getPath();
		}
		File file = new File(filePath);
		if (file == null || !file.exists()) {
			Toast.makeText(getApplicationContext(), "文件不存在", Toast.LENGTH_SHORT)
					.show();
			return;
		}
		if (file.length() > 10 * 1024 * 1024) {
			Toast.makeText(getApplicationContext(), "文件不能大于10M",
					Toast.LENGTH_SHORT).show();
			return;
		}

		File file_new = new File("/sdcard/Intimacy/user/Send/File", file + "");

		try {
			JSONArray sendArray = new JSONArray();
			JSONObject sendObject = new JSONObject();
			sendObject.put("sendid", sp_userMessage.getString("USER_NAME", ""));
			sendObject.put("receiveid", friendName);
			sendObject.put("message", filetoString(filePath));
			sendObject.put("time", System.currentTimeMillis());
			sendObject.put("type", 4);
			sendArray.put(sendObject);

			sendMessage(sendArray);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * onActivityResult
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) { // 清空消息
			if (requestCode == REQUEST_CODE_EMPTY_HISTORY) {
				// 清空会话

			} else if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片

				if (cameraFile != null && cameraFile.exists())
					Log.e("cameraFile.getAbsolutePath()------>>>>",
							cameraFile.getAbsolutePath());
				sendPicture(cameraFile.getAbsolutePath(), 0);

			} else if (requestCode == REQUEST_CODE_LOCAL) { // 发送本地图片

				if (data != null) {
					Uri selectedImage = data.getData();
					if (selectedImage != null) {
						sendPicByUri(selectedImage);
					}
				}

			} else if (requestCode == REQUEST_CODE_SELECT_FILE) { // 发送选择的文件

				if (data != null) {
					Uri uri = data.getData();
					if (uri != null) {
						sendFile(uri);
					}
				}

			} else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) {
				// 粘贴

			}
		}
	}

	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onPause() {
		super.onPause();
		// if (wakeLock.isHeld())
		// wakeLock.release();
	}

	/**
	 * 将图片转换为字符串
	 * 
	 * @param bitmap
	 * @return
	 */
	public String bitmaptoString(Bitmap bitmap) {

		// 将Bitmap转换成字符串
		String string = null;
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		return string;
	}

	/**
	 * 将字符串转换为文件
	 * 
	 * @param imgStr
	 * @param imgFilePath
	 * @return
	 */
	private boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null) // 图像数据为空
			return false;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] bytes = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(bytes);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 文件转为字符串
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static String filetoString(String path) throws Exception {

		File file = new File(path);
		InputStream inStream = new FileInputStream(file);
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		String mImage = new String(Base64.encodeToString(data, Base64.DEFAULT));
		outStream.close();
		inStream.close();
		return mImage;

	}

	/**
	 * 向服务器传输信息
	 * 
	 * @param jsonMessage
	 */
	private void sendMessage(final JSONArray jsonMessage) {

		new Thread() {

			public void run() {

				try {

					Log.e("message------", jsonMessage.toString());

					OutputStream outputStream;

					String message;

					Socket socket = new Socket(IP, PORT);
					outputStream = socket.getOutputStream();
					message = friendName + " " + jsonMessage.toString();
					byte[] send = message.getBytes();
					outputStream.write(send);
					outputStream.close();
					socket.close();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}

		}.start();

	}

	/**
	 * 时间转换
	 * 
	 * @param currentTime
	 * @return
	 */
	private String getTime(double currentTime) {

		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		Date curDate = new Date();
		String str = format.format(curDate);
		if (currentTime - oldTime >= 5000) {
			oldTime = currentTime;
			return str;
		} else {
			return " ";
		}

	}

	/**
	 * 将聊天记录存储到本地文件
	 * 
	 * @param jsonObject
	 */
	private void storeToFile(JSONObject jsonObject) {

		try {
			JSONArray jsonArray;

			if (!CacheUtil.getFromFile(
					friendName + "_"
							+ sp_userMessage.getString("USER_NAME", ""),
					"Send/Message").equals("")) {

				jsonArray = new JSONArray(CacheUtil.getFromFile(friendName
						+ "_" + sp_userMessage.getString("USER_NAME", ""),
						"Send/Message"));

				jsonArray.put(jsonObject);

			} else {

				jsonArray = new JSONArray();
				jsonArray.put(jsonObject);

			}

			CacheUtil
					.writeToFile(jsonArray.toString(), friendName + "_"
							+ sp_userMessage.getString("USER_NAME", ""),
							"Send/Message");

		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void getChatHistory() {

		try {

			JSONArray jsonArray;

			if (!CacheUtil.getFromFile(
					friendName + "_"
							+ sp_userMessage.getString("USER_NAME", ""),
					"Send/Message").equals("")) {

				jsonArray = new JSONArray(CacheUtil.getFromFile(friendName
						+ "_" + sp_userMessage.getString("USER_NAME", ""),
						"Send/Message"));

				for (int i = 0; i < jsonArray.length(); i++) {

					JSONObject jsonObject = (JSONObject) jsonArray.get(i);
					ListData listData;

					if (jsonObject.optInt("flag") == 1) {

						Bitmap friendPhoto = CacheUtil.GetFromFile(
								jsonObject.optString("receiveid"),
								"FriendPhoto");
						Bitmap myPhoto = CacheUtil.GetFromFile(
								jsonObject.optString("sendid"), "Photo");

						listData = new ListData(
								jsonObject.optString("receiveid"),
								jsonObject.optString("sendid"),
								jsonObject.optString("message"),
								jsonObject.optInt("flag"),
								getTime(jsonObject.optDouble("time")),
								friendPhoto, myPhoto, jsonObject.optInt("type"));
						messageLists.add(listData);

					} else {

						Bitmap friendPhoto = CacheUtil.GetFromFile(
								jsonObject.optString("sendid"), "FriendPhoto");
						Bitmap myPhoto = CacheUtil.GetFromFile(
								jsonObject.optString("receiveid"), "Photo");

						listData = new ListData(jsonObject.optString("sendid"),
								jsonObject.optString("receiveid"),
								jsonObject.optString("message"),
								jsonObject.optInt("flag"),
								getTime(jsonObject.optDouble("time")),
								friendPhoto, myPhoto, jsonObject.optInt("type"));
						messageLists.add(listData);

					}

				}

			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	public static void updateMessage(String friendname, String username,
			String content, int flag, String time, Bitmap friendPhoto,
			Bitmap userPhoto, int type) {

		ListData listData = new ListData(friendname, username, content, flag,
				time, friendPhoto, userPhoto, type);
		messageLists.add(listData);
		adapter.notifyDataSetChanged();
		listView.setSelection(listView.getCount() - 1);

	}
}
